//
//  AFNetworkHandler.m
//  UI22_项目框架
//
//  Created by 15 on 15/7/3.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "AFNetworkHandler.h"

@implementation AFNetworkHandler
// 参数1: 网络接口
// 参数2: 返回数据的block
+ (void)GETwithAFNByURL:(NSString *)urlstr completion:(void (^)(id))block
{
    
//    NSLog(@"%@", NSHomeDirectory());
    
    // 网址转码 处理中文字符
//    NSString *str = [urlstr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    // 创建AFN网络请求管理类
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    // 设置响应解析对象
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    // 设置数据支持类型
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/css", @"text/plain", nil]];
    // 建立沙盒
    NSArray *path =NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *pathString =path.lastObject;
    
    NSString *pathLast =[NSString stringWithFormat:@"/Caches/com.hackemist.SDWebImageCache.default/%lu.text", (unsigned long)[urlstr hash]];
    
    //创建字符串文件存储路径
    NSString *PathName =[pathString stringByAppendingString:pathLast];
    
    // AFN的GET请求
    [manager GET:urlstr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        // 写入文件
        [responseObject writeToFile:PathName atomically:YES];

        
        // 请求成功执行的地方
        // responseObject返回数据为NSData
        if (responseObject) {
            // 如果返回数据不为空, 则开始JSON解析
            id result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            // 通过block回调数据
            block(result);
        } else {
            NSLog(@"返回数据为空, 请检查");
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        // 请求失败执行的地方
        NSLog(@"请求失败: %@", error);
        
        // 没有网络申请的时候调用本地缓存
        if ([[NSFileManager defaultManager] fileExistsAtPath:PathName]) {
            //从本地读缓存文件
            NSData *responseObject = [NSData dataWithContentsOfFile:PathName];
            id result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            // 通过block回调数据
            block(result);
        }

        
    }];
    
    // 1.获得网络监控的管理者
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    
    // 2.设置网络状态改变后的处理
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        // 当网络状态改变了, 就会调用这个block
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
            {     // NSLog(@"未知网络");
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前为未知网络" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
                [alertView show];
                break;
            }
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
            {    // NSLog(@"没有网络(断网)");
                UIAlertView *alertView1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有网络" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
                [alertView1 show];
                
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
            {    // NSLog(@"手机自带网络");
//                                UIAlertView *alertView2 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前为手机自带网络" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
//                                [alertView2 show];
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
            {    //  NSLog(@"WIFI");
//                                UIAlertView *alertView3 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前为WIFI环境" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
//                                [alertView3 show];
                break;
            }
        }
    }];
    
    // 3.开始监控
    [mgr startMonitoring];

    
    
}

+ (void)GETwithUTF8AFNByURL:(NSString *)urlstr completion:(void (^)(id))block
{
    // 网址转码 处理中文字符
        NSString *str = [urlstr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    // 创建AFN网络请求管理类
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    // 设置响应解析对象
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    // 设置数据支持类型
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/css", @"text/plain", nil]];
    [manager.requestSerializer setValue:@"CNZZDATA1254192348=1058614802-1438681331-%7C1439287457" forHTTPHeaderField:@"Cookie"];
    
    // 建立沙盒
    NSArray *path =NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *pathString =path.lastObject;
    
    NSString *pathLast =[NSString stringWithFormat:@"/Caches/com.hackemist.SDWebImageCache.default/%lu.text", (unsigned long)[str hash]];
    
    //创建字符串文件存储路径
    NSString *PathName =[pathString stringByAppendingString:pathLast];
    
    
    // AFN的GET请求
    [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        // 请求成功执行的地方
        // responseObject返回数据为NSData
        if (responseObject) {
            
            // 写入文件
            [responseObject writeToFile:PathName atomically:YES];

            
            // 如果返回数据不为空, 则开始JSON解析
            id result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            // 通过block回调数据
            block(result);
        } else {
            
            
            
            NSLog(@"返回数据为空, 请检查");
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        // 没有网络申请的时候调用本地缓存
        if ([[NSFileManager defaultManager] fileExistsAtPath:PathName]) {
            //从本地读缓存文件
            NSData *responseObject = [NSData dataWithContentsOfFile:PathName];
            id result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            // 通过block回调数据
            block(result);
        }
        
        
        // 请求失败执行的地方
        NSLog(@"请求失败: %@", error);
    }];
    
    // 1.获得网络监控的管理者
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    
    // 2.设置网络状态改变后的处理
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        // 当网络状态改变了, 就会调用这个block
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
            {     // NSLog(@"未知网络");
//                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前为未知网络" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
//                [alertView show];
                break;
            }
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
            {    // NSLog(@"没有网络(断网)");
//                UIAlertView *alertView1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有网络" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
//                [alertView1 show];                
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
            {    // NSLog(@"手机自带网络");
                //                UIAlertView *alertView2 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前为手机自带网络" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
                //                [alertView2 show];
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
            {    //  NSLog(@"WIFI");
                //                UIAlertView *alertView3 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前为WIFI环境" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
                //                [alertView3 show];
                break;
            }
        }
    }];
    
    // 3.开始监控
    [mgr startMonitoring];
    
}

@end
